import MySQLdb
import time
import random
import operator

class sniffer:
    def __init__(self):
        self.db=MySQLdb.connect(host="localhost",user="root", passwd="",db="phone_tracker")
        self.db.query("""SELECT * FROM `resultset-location`""")
        r=self.db.use_result()
        self.sniffer = []
        for each in r.fetch_row(maxrows=0):
            self.sniffer.append(each)

    def add(self, name="-", mac="AABBCC"):
        c=self.db.cursor()
        c.executemany(
        """
        INSERT INTO `resultset-counts` (`hostname`, `device_type`, `mac_address`)
        VALUES (%s, %s, %s)
        """,
        [
        (name, "wifi", mac)
        ] )
        print "Added: ", "NAME:",name," MAC:", mac

    def view(self, rows=5):
        #db=MySQLdb.connect(host="localhost",user="root", passwd="",db="phone_tracker")
        self.db.query("""SELECT * FROM `resultset-counts` ORDER BY dt DESC""")
        r=self.db.use_result()
        print "VIEW"
        for each in r.fetch_row(rows):
            print each
    
    def clearscreen(numlines=100):
        """
        Clear the console.
        numlines is an optional argument used only as a fall-back.
        """
        import os
        if os.name == "posix":
            # Unix/Linux/MacOS/BSD/etc
            os.system('clear')
        elif os.name in ("nt", "dos", "ce"):
            # DOS/Windows
            os.system('CLS')
        else:
            # Fallback for other operating systems.
            print '\n' * numlines
    
    def move(self, mode, id, mac):
        if (mode == "rand"):
            newHost = random.randint(1, len(self.sniffer)+1)
            self.add(name="Host "+str(newHost), mac=mac)
        
        if("x" in mode):
            # long
            self.sorted_list = sorted(self.sniffer, key=operator.itemgetter(5))
        else:
            # lat
            self.sorted_list = sorted(self.sniffer, key=operator.itemgetter(6))
        
        for i in range(len(self.sorted_list)):
            if self.sorted_list[i][1] == id:
                newHost = self.sorted_list[i][1]
                try:
                    if "-" in mode:
                        if (i!=0):
                            newHost = self.sorted_list[i-1][1]
                    else:
                        newHost = self.sorted_list[i+1][1]
                except:
                    pass
                finally:
                    self.add(name=newHost, mac=mac)
                    return newHost
            
class incLetter:
    def __init__(self, name):
        self.name = name
    def __add__(self, other):
        for x in range(1, len(self.name)):
            a = list(self.name)[-1 * x]
            return self.name[:len(self.name)-x] + chr(ord(a) + other)
            
class node:
    def __init__(self, host, mac):
        self.host = host
        self.mac  = mac

# non-blocking input for windows
def kbfunc(): 
    import msvcrt 
    x = msvcrt.kbhit()
    if x: 
        ret = ord(msvcrt.getch()) 
    else: 
        ret = 0
    return ret
        
mysniffer = sniffer()
nodes = []
mac = incLetter('AABBCC')
for each in range(0,11):
    i = random.randint(0, len(mysniffer.sniffer)+1)
    nodes.append(node("Host "+str(i), mac+each))

run=True
mode = "rand"
count = False
while 1:
    mysniffer.clearscreen()
    print "Modes: x,-x,y,-y"
    input = kbfunc()
    if input:
        print ">>"
        mode = raw_input()
    if (run):
        # Settings
        # number people
        # END Settings
        #mode = "-y"
        print "Mode = "+str(mode)
        tmp = []
        for each in nodes:
            if (random.randint(1, 3)):
                time.sleep(random.randint(1,3))
                tmp.append(node(mysniffer.move(mode, each.host, each.mac), each.mac))
                
        nodes = tmp
        mysniffer.view()